<template>
  <div class="discussion-detail">
    <!-- 整合后的讨论和辩题卡片 -->
    <div class="debate-card-wrapper" v-if="discussion && debateVisible">
      <div class="debate-card">
        <div class="debate-header">
          <span class="debate-title">{{ discussion.title }}</span>
          <a-button
            type="text"
            class="close-btn"
            shape="circle"
            @click="closeDebate"
          >
            <close-outlined />
          </a-button>
        </div>

        <!-- 讨论描述 -->
        <div class="debate-description">
          <p>{{ discussion.content }}</p>
          <div class="publish-info">
            <span>发布时间：{{ formatDate(discussion.createTime) }}</span>
          </div>
        </div>

        <div class="debate-content">
          <div class="debate-sides">
            <!-- 正方 -->
            <div class="debate-side">
              <div class="side-container">
                <div class="side-image">
                  <img :src="discussion.positiveImage" alt="正方观点" />
                </div>
                <div class="side-content">
                  <p>{{ discussion.positiveContent }}</p>
                  <div
                    class="vote-count"
                    v-if="discussion.userVoteStatus !== 0"
                  >
                    <like-outlined /> {{ discussion.positiveVotes || 0 }} 人支持
                  </div>
                </div>
              </div>
            </div>

            <!-- VS标志 -->
            <div class="vs-container">
              <div class="vs-text">VS</div>
            </div>

            <!-- 反方 -->
            <div class="debate-side">
              <div class="side-container">
                <div class="side-image">
                  <img :src="discussion.negativeImage" alt="反方观点" />
                </div>
                <div class="side-content">
                  <p>{{ discussion.negativeContent }}</p>
                  <div
                    class="vote-count"
                    v-if="discussion.userVoteStatus !== 0"
                  >
                    <dislike-outlined />
                    {{ discussion.negativeVotes || 0 }} 人支持
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 投票按钮区域 -->
          <div class="voting-section">
            <a-button
              class="vote-btn positive-btn"
              :class="{ voted: discussion.userVoteStatus === 1 }"
              @click="handleVote(1)"
              :disabled="discussion.userVoteStatus !== 0"
            >
              {{ discussion.userVoteStatus === 1 ? "已投正方" : "支持正方" }}
            </a-button>

            <a-button
              class="vote-btn negative-btn"
              :class="{ voted: discussion.userVoteStatus === 2 }"
              @click="handleVote(2)"
              :disabled="discussion.userVoteStatus !== 0"
            >
              {{ discussion.userVoteStatus === 2 ? "已投反方" : "支持反方" }}
            </a-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论区域 -->
    <a-card class="comments-card" title="评论区">
      <!--      <h3 class="comments-title">评论 ({{ comments.length }})</h3>-->
      <a-list
        v-if="comments.length"
        :data-source="comments"
        :loading="commentsLoading"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-comment
              :author="item.userName"
              :avatar="item.userAvatar || defaultAvatar"
            >
              <template #datetime>
                <span class="date-vote-container">
                  {{ formatDate(item.createTime) }}
                  <span v-if="item.userVoteStatus === 1" class="positive-badge"
                    >正方</span
                  >
                  <span v-if="item.userVoteStatus === 2" class="negative-badge"
                    >反方</span
                  >
                </span>
              </template>
              <template #content>
                <div
                  class="comment-content"
                  :class="{
                    'positive-vote': item.userVoteStatus === 1,
                    'negative-vote': item.userVoteStatus === 2,
                  }"
                >
                  <p>{{ item.content }}</p>
                </div>
              </template>
              <template #actions>
                <span @click="likeComment(item.id)">
                  <like-outlined />
                  {{ item.likeCount }}
                </span>
                <span @click="replyToComment(item.id, item.userName)">
                  回复
                </span>
                <span class="expand-replies" @click="toggleReplies(item.id)">
                  {{ isExpanded(item.id) ? "收起回复" : "展开回复" }}
                </span>
              </template>
              <template
                v-if="isExpanded(item.id) && getReplies(item.id).length > 0"
              >
                <div class="comment-replies">
                  <a-list :data-source="getReplies(item.id)">
                    <template #renderItem="{ item: reply }">
                      <a-list-item>
                        <a-comment
                          :author="reply.userName"
                          :avatar="reply.userAvatar || defaultAvatar"
                        >
                          <template #datetime>
                            <span class="date-vote-container">
                              {{ formatDate(reply.createTime) }}
                              <span
                                v-if="reply.userVoteStatus === 1"
                                class="positive-badge"
                                >正方</span
                              >
                              <span
                                v-if="reply.userVoteStatus === 2"
                                class="negative-badge"
                                >反方</span
                              >
                            </span>
                          </template>
                          <template #content>
                            <div
                              class="reply-content"
                              :class="{
                                'positive-vote': reply.userVoteStatus === 1,
                                'negative-vote': reply.userVoteStatus === 2,
                              }"
                            >
                              <p>
                                回复 {{ reply.parentUserName }}：{{
                                  reply.content
                                }}
                              </p>
                            </div>
                          </template>
                          <template #actions>
                            <span @click="likeComment(reply.id)">
                              <like-outlined />
                              {{ reply.likeCount }}
                            </span>
                            <span
                              @click="
                                replyToComment(
                                  reply.id,
                                  reply.userName,
                                  item.id
                                )
                              "
                            >
                              回复
                            </span>
                          </template>
                        </a-comment>
                      </a-list-item>
                    </template>
                  </a-list>
                </div>
              </template>
            </a-comment>
          </a-list-item>
        </template>
      </a-list>
      <div v-else-if="!commentsLoading" class="no-comments">暂无评论</div>

      <!-- 评论编辑器 -->
      <div class="comment-editor">
        <a-comment>
          <template #content>
            <div class="reply-header" v-if="replyTo.type !== 'none'">
              <span class="reply-tip">
                {{ replyTo.type === "reply" ? "回复二级评论" : "回复评论" }}：
                @{{ replyTo.parentUsername }}
              </span>
              <a-button type="link" @click="cancelReply">取消回复</a-button>
            </div>
            <a-form-item>
              <a-textarea
                v-model:value="commentContent"
                :rows="4"
                :placeholder="
                  replyTo.type === 'none'
                    ? '写下你的评论...'
                    : '写下你的回复...'
                "
              />
            </a-form-item>
            <a-form-item>
              <a-button
                type="primary"
                :loading="submitting"
                @click="handleSubmitComment"
              >
                {{ replyTo.type === "none" ? "发表评论" : "发表回复" }}
              </a-button>
            </a-form-item>
          </template>
        </a-comment>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { message } from "ant-design-vue";
import {
  LikeOutlined,
  DislikeOutlined,
  CloseOutlined,
} from "@ant-design/icons-vue";

const defaultAvatar = "https://joeschmoe.io/api/v1/random";
import type API from "@/api";
import {
  getDiscussionByIdUsingGet,
  voteUsingPost,
} from "@/api/culturePartDiscussionController";

import {
  getDiscussionCommentsUsingGet,
  getCommentRepliesUsingGet,
  addCommentUsingPost,
  likeCommentUsingPost,
} from "@/api/culturePartCommentController";

const route = useRoute();
const loading = ref(true);
const commentsLoading = ref(true);
const submitting = ref(false);
const discussion = ref<API.CulturePartDiscussion>();
const comments = ref<API.CulturePartComment[]>([]);
const repliesMap = ref<Record<string, API.CulturePartComment[]>>({});
const commentContent = ref("");
const expandedComments = ref<Set<number>>(new Set());
const debateVisible = ref(true);

// 添加回复状态管理
interface ReplyTo {
  type: "none" | "comment" | "reply";
  commentId?: number;
  parentId?: number;
  parentUsername?: string;
}

const replyTo = ref<ReplyTo>({ type: "none" });

const formatDate = (dateStr: string | undefined) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return date.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

const fetchDiscussion = async () => {
  try {
    const res = await getDiscussionByIdUsingGet({
      id: Number(route.params.id),
    });
    if (res.data.code === 0 && res.data.data) {
      discussion.value = res.data.data;
    }
  } catch (error) {
    message.error("获取讨论详情失败");
  } finally {
    loading.value = false;
  }
};

const handleVote = async (voteType: number) => {
  if (!discussion.value) return;

  // 如果用户已经投过票，提示不能重复投票
  if (discussion.value.userVoteStatus !== 0) {
    message.warning("您已经参与过投票，不能重复投票");
    return;
  }

  try {
    const res = await voteUsingPost({
      discussionId: Number(route.params.id),
      voteType: voteType, // 1: 正方, 2: 反方
    });

    if (res.data.code === 0 && res.data.data) {
      message.success("投票成功");
      // 更新投票状态
      if (discussion.value) {
        discussion.value.userVoteStatus = voteType;
        if (voteType === 1) {
          discussion.value.positiveVotes =
            (discussion.value.positiveVotes || 0) + 1;
        } else {
          discussion.value.negativeVotes =
            (discussion.value.negativeVotes || 0) + 1;
        }
      }
    } else {
      message.error(res.data.message || "投票失败");
    }
  } catch (error) {
    message.error("投票失败，请稍后再试");
  }
};

const closeDebate = () => {
  debateVisible.value = false;
};

const fetchComments = async () => {
  try {
    const res = await getDiscussionCommentsUsingGet({
      discussionId: Number(route.params.id),
    });
    if (res.data.code === 0 && res.data.data) {
      comments.value = res.data.data;
      console.log("获取到的评论数据:", comments.value);
      // 添加debugger，便于调试
      if (process.env.NODE_ENV !== "production") {
        debugger;
      }
    }
  } catch (error) {
    message.error("获取评论失败");
  } finally {
    commentsLoading.value = false;
  }
};

const handleSubmitComment = async () => {
  if (!commentContent.value.trim()) {
    message.warning("请输入评论内容");
    return;
  }

  submitting.value = true;
  try {
    // 构造评论数据
    const commentData: {
      discussionId: number;
      content: string;
      parentId?: number;
      parentUserName?: string;
    } = {
      discussionId: Number(route.params.id),
      content: commentContent.value.trim(),
    };

    // 根据不同的回复类型设置参数
    if (replyTo.value.type === "comment") {
      // 回复一级评论
      commentData.parentId = Number(replyTo.value.commentId);
      commentData.parentUserName = replyTo.value.parentUsername || "";
    } else if (replyTo.value.type === "reply") {
      // 回复二级评论
      commentData.parentId = Number(replyTo.value.commentId);
      commentData.parentUserName = replyTo.value.parentUsername || "";
    }

    console.log("发送评论数据:", commentData); // 调试日志

    const response = await addCommentUsingPost(
      commentData as API.CulturePartComment
    );

    if (response.data?.code === 0) {
      message.success("评论成功");
      commentContent.value = "";
      replyTo.value = { type: "none" };
      await fetchComments();
    } else {
      message.error(response.data?.message || "评论失败");
    }
  } catch (error) {
    console.error("评论失败:", error);
    message.error("评论失败");
  } finally {
    submitting.value = false;
  }
};

const likeComment = async (commentId: number) => {
  try {
    await likeCommentUsingPost({
      commentId,
    });
    await fetchComments();
    message.success("点赞成功");
  } catch (error) {
    message.error("点赞失败");
  }
};

const replyToComment = (
  commentId: number,
  username: string,
  parentId?: number
) => {
  if (parentId && parentId !== commentId) {
    // 回复二级评论
    replyTo.value = {
      type: "reply",
      commentId: parentId, // 一级评论的ID
      parentUsername: username || "", // 二级评论的用户名
    };
  } else {
    // 回复一级评论
    replyTo.value = {
      type: "comment",
      commentId: commentId,
      parentUsername: username || "",
    };
  }
  const commentEditor = document.querySelector(".comment-editor");
  commentEditor?.scrollIntoView({ behavior: "smooth" });
};

const cancelReply = () => {
  replyTo.value = { type: "none" };
  commentContent.value = "";
};

const toggleReplies = async (commentId: number) => {
  if (expandedComments.value.has(commentId)) {
    expandedComments.value.delete(commentId);
  } else {
    try {
      const res = await getCommentRepliesUsingGet({
        commentId: commentId,
      });
      if (res.data?.code === 0 && res.data.data) {
        repliesMap.value[commentId] = res.data.data;
        expandedComments.value.add(commentId);
      }
    } catch (error) {
      console.error("加载回复失败:", error);
      message.error("获取回复失败");
    }
  }
};

const isExpanded = (commentId: number) => {
  return expandedComments.value.has(commentId);
};

const getReplies = (commentId: number) => {
  return repliesMap.value[commentId] || [];
};

onMounted(() => {
  fetchDiscussion();
  fetchComments();
});
</script>

<style scoped>
.discussion-detail {
  width: 100%;
  min-height: 100vh;
  padding: 8vh 0 10vh;
  background: url("@/assets/background/discussiondetailbackground.png")
    no-repeat center top;
  background-size: cover;
  position: relative;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  gap: 3rem;
}

.discussion-detail::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0.2),
    rgba(0, 0, 0, 0.1)
  );
  z-index: 1;
}

.debate-card-wrapper,
.comments-card {
  max-width: 95vw;
  width: 800px;
  margin: 0 auto;
  position: relative;
  z-index: 2;
}

:deep(.ant-card) {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 1rem;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
}

/* 辩论卡片样式 */
.debate-card {
  background: #e1d8cf;
  border-radius: 1rem;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.debate-header {
  background: #62432d;
  color: #fff;
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.debate-title {
  font-size: 1.3rem;
  font-weight: bold;
}

.close-btn {
  color: #fff;
}

/* 讨论描述区域 */
.debate-description {
  padding: 1.5rem;
  background: rgba(255, 255, 255, 0.9);
  border-bottom: 1px solid #e8e8e8;
}

.debate-description p {
  font-size: 1rem;
  line-height: 1.6;
  color: #333;
  margin-bottom: 1rem;
}

.publish-info {
  font-size: 0.9rem;
  color: #666;
}

.debate-content {
  padding: 1.5rem;
  background: #f5f2ea;
}

.debate-sides {
  display: flex;
  justify-content: space-between;
  align-items: stretch;
  margin-bottom: 1.5rem;
}

.debate-side {
  flex: 0 0 calc(45% - 1rem);
}

.vs-container {
  flex: 0 0 10%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.vs-text {
  font-size: 2.5rem;
  font-weight: bold;
  color: #62432d;
}

.side-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  height: 100%;
}

.side-image {
  width: 100%;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.side-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.side-content {
  background: rgba(255, 255, 255, 0.8);
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.side-content p {
  font-size: 0.9rem;
  line-height: 1.5;
  color: #333;
  margin-bottom: 0.5rem;
  flex-grow: 1;
}

.vote-count {
  text-align: right;
  color: #666;
  font-size: 0.85rem;
  margin-top: auto;
}

/* 投票按钮区域 */
.voting-section {
  display: flex;
  justify-content: space-between;
  gap: 2rem;
}

.vote-btn {
  height: 44px;
  font-size: 1rem;
  font-weight: bold;
  border-radius: 8px;
  flex: 1;
}

.positive-btn {
  background: #d73f3f;
  border-color: #d73f3f;
  color: white;
}

.positive-btn:hover:not(:disabled) {
  background: #e05454;
  border-color: #e05454;
}

.negative-btn {
  background: #2d609b;
  border-color: #2d609b;
  color: white;
}

.negative-btn:hover:not(:disabled) {
  background: #3a70ae;
  border-color: #3a70ae;
}

.vote-btn.voted {
  opacity: 0.8;
}

.vote-btn:disabled {
  color: white;
  opacity: 0.7;
}

/* 评论区样式 */
.comments-title {
  margin-bottom: 1.5rem;
  font-size: 1.3rem;
  color: #62432d;
}

.content {
  margin: 20px 0;
  line-height: 1.6;
}

.comments-section {
  margin-top: 40px;
}

.comment-editor {
  margin-top: 20px;
}

.no-comments {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

.comment-replies {
  margin-left: 24px;
  margin-top: 16px;
  border-left: 1px solid rgba(240, 240, 240, 0.8);
  padding-left: 16px;
  transition: all 0.3s ease-in-out;
}

.expand-replies {
  cursor: pointer;
  color: #1890ff;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.expand-replies:hover {
  color: #40a9ff;
}

.reply-content {
  margin-bottom: 8px;
}

.comment-replies .ant-comment-actions {
  margin-top: 8px;
}

.comment-replies .ant-list-item {
  padding: 12px 0;
}

.comment-replies .ant-comment-content {
  padding: 16px;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding: 8px;
  background-color: rgba(245, 245, 245, 0.9);
  border-radius: 4px;
  backdrop-filter: blur(5px);
}

.reply-tip {
  color: #666;
  font-size: 14px;
}

/* 添加评论投票样式 */
.comment-content,
.reply-content {
  position: relative;
  padding: 0.5rem;
  border-radius: 4px;
}

.positive-vote {
  background-color: rgba(215, 63, 63, 0.05);
  border-left: 3px solid #d73f3f;
}

.negative-vote {
  background-color: rgba(45, 96, 155, 0.05);
  border-left: 3px solid #2d609b;
}

.vote-badge {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
}

.positive-badge {
  background-color: #d73f3f;
  color: white;
  font-size: 0.75rem;
  padding: 0.15rem 0.4rem;
  border-radius: 4px;
  margin-left: 8px;
  display: inline-block;
}

.negative-badge {
  background-color: #2d609b;
  color: white;
  font-size: 0.75rem;
  padding: 0.15rem 0.4rem;
  border-radius: 4px;
  margin-left: 8px;
  display: inline-block;
}

/* 添加日期和投票标识的容器样式 */
:deep(.ant-comment-datetime) {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.date-vote-container {
  display: flex;
  align-items: center;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .debate-sides {
    flex-direction: column;
    align-items: center;
    gap: 2rem;
  }

  .debate-side {
    flex: 0 0 100%;
    width: 100%;
  }

  .vs-container {
    height: auto;
    margin: 1rem 0;
  }
}
</style>
